from django.shortcuts import render
from commodity.models import CommodityInfos,Types
# Create your views here.
def indexView(request):
    title="首页"
    classContent=""
    commodityInfos=CommodityInfos.objects.order_by("_sold").all()[:8]
    types=Types.objects.all()
    c1=[x.seconds for x in types if x.firsts=='儿童服饰']
    clothes=CommodityInfos.objects.filter(types__in=c1).order_by('-sold')[:5]
    f1=[x.seconds for x in types if x.firsts=='奶粉辅食']
    food=CommodityInfos.objects.filter(types__in=f1).order_by('-sold')[:5]
    g1=[x.seconds for x in types if x.firsts=='儿童用品']
    goods=CommodityInfos.objects.filter(types__in=g1).order_by('-sold')[:5]
    #将所有变量传递给模板进行渲染
    return render(request,'index.html',locals())
#基于类的视图请求，处理首页的请求，功能和indexView相同
class indexClassView(TemplateView):
    #指定渲染模板
    template_name='index.html'
    #可选，指定模板引擎
    template_type=engine=None
    content_type=None
    #额外上模板上下文的变量
    extra_context={'title':'首页','classContent':''}
    #重写上下文数据的方法
def get_context_data(self,**kwargs):
    #获取父类的上下文
    context=super(inderxClassView,self).get_context_data(**kwargs)
    #获取销量最高的八个商品
    context['commodityInfos']=CommodityInfos.objects.order_by("-sold").all()[:8]
    types=Types.objects.all()
    c1 = [x.seconds for x in types if x.firsts == '儿童服饰']
    context['clothes'] = CommodityInfos.objects.filter(types__in=c1).order_by('-sold')[:5]
    f1 = [x.seconds for x in types if x.firsts == '奶粉辅食']
    context['food'] = CommodityInfos.objects.filter(types__in=f1).order_by('-sold')[:5]
    g1 = [x.seconds for x in types if x.firsts == '儿童用品']
    context['goods'] = CommodityInfos.objects.filter(types__in=g1).order_by('-sold')[:5]
    return context

def get(self,request,*args,**kwargs):
    """

    """
    context=self.get_cotext_data(**kwargs)
    return self.render_to_response(context)

def post(self,request,*args,**kwargs):
    """
    处理http的post请求
    """
    context = self.get_cotext_data(**kwargs)
    return self.render_to_response(context)


def page_not_found():
    return render(request,'404.html',status=404)

def page_error():
    return render(request,'500.html',status=500)